package com.castle.fortress.admin.study.course.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.annotation.CastleLog;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.member.dto.MemberDto;
import com.castle.fortress.admin.study.course.dto.StudyCourseChapterCoursewareDto;
import com.castle.fortress.admin.study.course.dto.StudyCourseLogDto;
import com.castle.fortress.admin.study.course.dto.StudyCoursewareDto;
import com.castle.fortress.admin.study.course.entity.StudyCourseLogEntity;
import com.castle.fortress.admin.study.course.entity.StudyCoursewareEntity;
import com.castle.fortress.admin.study.course.service.*;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.CourseStudyStatusEnum;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 课程记录表 api 控制器
 *
 * @author castle
 * @since 2023-02-14
 */
@Api(tags = "课程记录表api管理控制器")
@RestController
@RequestMapping("/api/study/course/studyCourseLog")
public class ApiStudyCourseLogController {
    @Autowired
    private StudyCourseLogService studyCourseLogService;
    @Autowired
    private StudyCourseChapterCoursewareService studyCourseChapterCoursewareService;
    @Autowired
    private StudyCourseChapterService studyCourseChapterService;
    @Autowired
    private StudyCourseService studyCourseService;
    @Autowired
    private StudyCoursewareService studyCoursewareService;


    /**
     * 课程记录表的分页展示
     *
     * @param studyCourseLogDto 课程记录表实体类
     * @param currentPage       当前页
     * @param size              每页记录数
     * @return
     */
    @CastleLog(operLocation = "课程记录表-api", operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程记录表分页展示")
    @GetMapping("/page")
    public RespBody<IPage<StudyCourseLogDto>> pageStudyCourseLog(StudyCourseLogDto studyCourseLogDto, @RequestParam(required = false) Integer currentPage, @RequestParam(required = false) Integer size) {
        Integer pageIndex = currentPage == null ? GlobalConstants.DEFAULT_PAGE_INDEX : currentPage;
        Integer pageSize = size == null ? GlobalConstants.DEFAULT_PAGE_SIZE : size;
        Page<StudyCourseLogDto> page = new Page(pageIndex, pageSize);

        IPage<StudyCourseLogDto> pages = studyCourseLogService.pageStudyCourseLog(page, studyCourseLogDto);
        return RespBody.data(pages);
    }

    /**
     * 课程记录表保存
     *
     * @param studyCourseLogDto 课程记录表实体类
     * @return
     */
    @CastleLog(operLocation = "课程记录表-api", operType = OperationTypeEnum.INSERT)
    @ApiOperation("课程记录表保存")
    @PostMapping("/save")
    public RespBody<String> saveStudyCourseLog(@RequestBody StudyCourseLogDto studyCourseLogDto) {
        MemberDto member = WebUtil.currentMember();
        if (member == null) {
            throw new BizException(GlobalRespCode.NO_LOGIN_ERROR);
        }
        if (studyCourseLogDto == null) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCourseChapterCoursewareDto queryDto = new StudyCourseChapterCoursewareDto();
        queryDto.setCourseId(studyCourseLogDto.getCourseId());
        queryDto.setIsDeleted(YesNoEnum.NO.getCode());
        List<StudyCourseChapterCoursewareDto> coursewareDtos = studyCourseChapterCoursewareService.listStudyCourseChapterCourseware(queryDto);
        if (coursewareDtos.size() < 1) {
            return RespBody.fail("该课程暂未添加课件，请联系管理员");
        }
        List<StudyCourseLogEntity> list = new ArrayList<>();
        for (StudyCourseChapterCoursewareDto dto : coursewareDtos) {
            StudyCourseLogEntity entity = new StudyCourseLogEntity();
            entity.setCourseId(dto.getCourseId());
            entity.setStatus(CourseStudyStatusEnum.NO_START.getCode());
            entity.setChapterId(dto.getChapterId());
            entity.setCoursewareId(dto.getCoursewareId());
            entity.setCreateTime(new Date());
            entity.setMemberId(member.getId());
            list.add(entity);
        }
        if (studyCourseLogService.saveBatch(list)) {
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程记录表编辑
     *
     * @param studyCourseLogDto 课程记录表实体类
     * @return
     */
    @CastleLog(operLocation = "课程记录表-api", operType = OperationTypeEnum.UPDATE)
    @ApiOperation("课程记录表编辑")
    @PostMapping("/edit")
    public RespBody<String> updateStudyCourseLog(@RequestBody StudyCourseLogDto studyCourseLogDto) {
        MemberDto member = WebUtil.currentMember();
        if (member == null) {
            throw new BizException(GlobalRespCode.NO_LOGIN_ERROR);
        }
        if (CommonUtil.verifyParamNull(studyCourseLogDto, studyCourseLogDto.getCourseId(), studyCourseLogDto.getChapterId(), studyCourseLogDto.getCoursewareId(), studyCourseLogDto.getStudyTime())) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        StudyCoursewareEntity courseware = studyCoursewareService.getById(studyCourseLogDto.getCoursewareId());
        if (studyCourseLogDto.getStudyTime() > 0) {
            if (courseware.getStudyTime() * 60 > studyCourseLogDto.getStudyTime()) {
                studyCourseLogDto.setStatus(CourseStudyStatusEnum.ONGOING.getCode());
            } else {
                studyCourseLogDto.setStatus(CourseStudyStatusEnum.FINISHED.getCode());
            }
        }
        StudyCourseLogEntity studyCourseLogEntity = ConvertUtil.transformObj(studyCourseLogDto, StudyCourseLogEntity.class);
        studyCourseLogEntity.setMemberId(member.getId());
        if (studyCourseLogService.updateStudyCourseLog(studyCourseLogEntity)) {
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程记录表删除
     *
     * @param ids 课程记录表id集合
     * @return
     */
    @CastleLog(operLocation = "课程记录表-api", operType = OperationTypeEnum.DELETE)
    @ApiOperation("课程记录表删除")
    @PostMapping("/delete")
    public RespBody<String> deleteStudyCourseLog(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if (studyCourseLogService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        } else {
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 课程记录表详情
     *
     * @param studyCourseLogDto 课程记录表
     * @return
     */
    @CastleLog(operLocation = "课程记录表-api", operType = OperationTypeEnum.QUERY)
    @ApiOperation("课程记录表详情")
    @PostMapping("/info")
    public RespBody<StudyCoursewareDto> infoStudyCourseLog(@RequestBody StudyCourseLogDto studyCourseLogDto) {
        MemberDto member = WebUtil.currentMember();
        if (member == null) {
            throw new BizException(GlobalRespCode.NO_LOGIN_ERROR);
        }
        if (CommonUtil.verifyParamNull(studyCourseLogDto, studyCourseLogDto.getCourseId(), studyCourseLogDto.getChapterId(), studyCourseLogDto.getCoursewareId())) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        QueryWrapper<StudyCourseLogEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", studyCourseLogDto.getCourseId());
        wrapper.eq("chapter_id", studyCourseLogDto.getChapterId());
        wrapper.eq("courseware_id", studyCourseLogDto.getCoursewareId());
        wrapper.eq("member_id", member.getId());
        StudyCourseLogEntity studyCourseLogEntity = studyCourseLogService.getOne(wrapper);
        StudyCoursewareDto dto = studyCoursewareService.getByIdExtends(studyCourseLogDto.getCoursewareId());
        if (studyCourseLogEntity != null) {
            dto.setStudyStatus(studyCourseLogEntity.getStatus());
            dto.setAlreadyStudyTime(studyCourseLogEntity.getStudyTime());
            dto.setLogId(studyCourseLogEntity.getId());
        //新增课件
        }else {
            dto.setStudyStatus(CourseStudyStatusEnum.NO_START.getCode());
            dto.setAlreadyStudyTime(0);
            studyCourseLogEntity = ConvertUtil.transformObj(studyCourseLogDto,StudyCourseLogEntity.class);
            studyCourseLogEntity.setMemberId(member.getId());
            studyCourseLogEntity.setStudyTime(dto.getAlreadyStudyTime());
            studyCourseLogEntity.setStatus(dto.getStudyStatus());
            studyCourseLogEntity.setCreateTime(new Date());
            studyCourseLogService.save(studyCourseLogEntity);
            dto.setLogId(studyCourseLogEntity.getId());
        }
        dto.setCourseId(studyCourseLogDto.getCourseId());
        dto.setChapterId(studyCourseLogDto.getChapterId());

        return RespBody.data(dto);
    }


}
